'use strict';

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');

module.exports = class LotteryController extends Controller {

	// 抽奖配置
	async data() {
		let response = {
			datas: {},
			msg: '',
			code: 1
		};
		
		const start = Date.now();
		
		// 查询抽奖配置表
		const lotteryParameterRes = await this.db.collection('usemall-lottery-parameter')
			.limit(1)
			.get();
			
		const [lotteryParameter] = lotteryParameterRes.data;
		
		if (lotteryParameter.state === 0) {
			response.msg = '抽奖功能未启用';
			return response;
		}
		
		const prizes = lotteryParameter.prizes || [];
		if (!prizes.length) {
			response.msg = '抽奖的奖品未配置';
			return response;
		}
		
		response.datas = lotteryParameter;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 开始抽奖
	async draw() {
		let response = {
			datas: {},
			msg: '',
			code: 1
		};
		
		const start = Date.now();
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		// 查询抽奖配置表
		const lotteryParameterRes = await this.db.collection('usemall-lottery-parameter')
			.limit(1)
			.get();
			
		const [lotteryParameter] = lotteryParameterRes.data;
		
		if (lotteryParameter.state === 0) {
			response.msg = '抽奖功能未启用';
			return response;
		}
		
		const prizes = lotteryParameter.prizes || [];
		if (!prizes.length) {
			response.msg = '抽奖的奖品未配置';
			return response;
		}
		
		// 查询用户所剩积分
		const memberRes = await this.db.collection('usemall-member').doc(uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();
		
		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];
		}
		const uname = memberData.member_nickname;
		// 当前积分
		const integral = memberData.member_integral;
		if (lotteryParameter.consume_integral > integral) {
			response.msg = `当前积分不足`;
			return response;
		}
		
		try{
			
			// 随机查询一条奖品池奖品
			const res = await this.db.collection('usemall-lottery-pool')
				.aggregate()
				.project({
					idx: 1,
					lottery_id: 1
				})
				.sample({
					size: 1
				})
				.end();
				
			const [lottery] = res.data;
			if (!(lottery && lottery._id)) {
				response.msg = '奖品已抽光，请明天早点来';
				return response;
			}
			
			// 开启事务
			const dbtran = await this.db.startTransaction();
			
			try {
				// 扣减用户积分
				// 记录积分
				// 事务模式
				await this.service.integral.decrease(uid, uname, { 
					integral: lotteryParameter.consume_integral, 
					source: '积分抽奖', 
					order_id: '', 
					goods_id: ''
				}, dbtran);
				
				// 判断积分是否大于等于0
				const memberIntegralRes = await this.db.collection('usemall-member').doc(uid).field({
					member_integral: true
				}).get();
				
				if (memberIntegralRes.data.member_integral < 0) {
					await dbtran.rollback();
					response.msg = '当前可用积分不足';
					return response;
				}
				
				// 提交事务
				await dbtran.commit();
				
				// 删除已抽奖品
				await this.db.collection('usemall-lottery-pool').doc(lottery._id).remove();
				
				// 奖品
				const prize = prizes.find(x => x.id == lottery.lottery_id);
				// 记录抽奖
				await this.db.collection('usemall-lottery-record').add({
					lottery_id: lottery.lottery_id,
					prize: prize,
					is_delete: 0,
					create_time: Date.now(),
					create_uid: uid,
					create_uname: uname
				});
				
				// 奖励抽奖
				if (prize) {
					if (prize.type == 1) {
						lottery.prize_desc = `恭喜，抽中${prize.name}`;
						
						if (prize.integral) {
							// 奖励积分
							await this.service.integral.increase(uid, uname, {
								source: '抽奖奖励',
								integral: prize.integral
							});
							lottery.prize_desc = `恭喜，+${prize.integral}积分`;
						}
					}
					
					if (prize.type == 2) {
						lottery.prize_desc = `谢谢参与，继续加油`;
					}
				}
				
				response.code = 0;
				response.datas = lottery;
			
			} catch (e) {
				// 回滚事务
				await dbtran.rollback();
				
				response.code = 500;
				response.msg = e;
			
				// 记录日志
				console.log('lottery/draw catch 2', e);
			}
		
		} catch(e) {
			console.log('lottery/draw catch 1', e);
		}
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
}
